package com.aabte.lota.auth.common.mybatis;

import com.aabte.lota.auth.auth.token.payload.TokenPayloadDTO;
import com.aabte.lota.auth.common.util.UserUtils;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import java.time.LocalDateTime;
import javax.annotation.Resource;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

/** 处理新增和更新的基础数据填充，配合BaseEntity和MyBatisPlusConfig使用 */
@Component
public class FillMetaHandler implements MetaObjectHandler {

  @Resource private UserUtils userUtils;

  /** 新增数据执行 */
  @Override
  public void insertFill(MetaObject metaObject) {
    TokenPayloadDTO user = userUtils.getUser();
    this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
    this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    this.strictInsertFill(metaObject, "createBy", String.class, String.valueOf(user.getUid()));
    this.strictInsertFill(metaObject, "updateBy", String.class, String.valueOf(user.getUid()));
  }

  /** 更新数据执行 */
  @Override
  public void updateFill(MetaObject metaObject) {
    TokenPayloadDTO user = userUtils.getUser();
    this.strictInsertFill(metaObject, "update_time", LocalDateTime.class, LocalDateTime.now());
    this.strictInsertFill(metaObject, "update_by", String.class, String.valueOf(user.getUid()));
  }
}
